
import { getUserInfo } from "../../utils/auth"
const getDefaultState = () => {
  return {
    // token: getToken(),
    userInfo: getUserInfo(),
  }
}

const state = getDefaultState()

const mutations = {
  changeState: (state, val) => {
    state.userInfo = val
  }
}

const actions = {
  async login({ commit, dispatch }, userInfo) {
    const { mblPhNo, password } = userInfo
    let loginRes
    try {
      loginRes = await login({ mblPhNo: mblPhNo.trim(), password: sha256(md5(password)) })

    } catch (error) {
      Message.error('登录失败，请稍后再试')

    }
    if (!checkRes(loginRes)) return
    if(loginRes.data.code === '2'){
      Message.warning(loginRes.data.msg)
    }
    if(loginRes.data.token){

      commit('SET_TOKEN', loginRes.data.token)
      const infoRes = await getInfo()
      if (!checkRes(infoRes)) return
      commit('SET_USERINFO', infoRes.data)
    }
    if(loginRes.data.code === '1'){
      commit('SET_LOGININFO','2')
      Message.error(loginRes.data.msg)

    }else {
      commit('SET_LOGININFO','1')
    }
    // let roleId = getRoleId()
    // if (infoRes.data.role.every((id) => id !== roleId)) {
    //   roleId = infoRes.data.role[0]
    // }
    // const authRes = await getAuth(roleId)
    // commit('SET_ROLEID', roleId)
    // if (!checkRes(authRes)) return
    // // await dispatch('genMenu')
    // commit('SET_STATE', ['queryed', true])
    return loginRes
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
